import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/record/channel_filter_logic.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/entity/record/channel_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'items/select_item_widget.dart';

class ChannelFilterPage extends StatefulWidget {
  const ChannelFilterPage({super.key, this.type});

  final int? type;

  @override
  State<ChannelFilterPage> createState() => _ChannelFilterPageState();
}

class _ChannelFilterPageState extends State<ChannelFilterPage> {
  late final ChannelFilterLogic logic =
      Get.put(ChannelFilterLogic(), tag: "${Get.arguments ?? widget.type}");

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChannelFilterLogic>(
        tag: "${Get.arguments ?? widget.type}",
        initState: (state) {
          logic.channelType = Get.arguments ?? widget.type;
        },
        builder: (logic) {
          return Scaffold(
            appBar: AppBar(
              leading: Align(
                alignment: Alignment.center,
                child: Image.asset(Utils.getImgPath("bottomsheet_close.png"),
                        width: 24, height: 24)
                    .tap(
                  () async {
                    if (logic.editable) {
                      bool? result = await Get.dialog(QsDialog.alert(
                          "您的编辑未完成，是否保存后退出",
                          confirmText: "是",
                          cancelText: "否"));
                      if (result == true) await logic.updateMyChannels();
                      Get.back();
                    } else {
                      Get.back();
                    }
                  },
                ),
              ),
              actions: [
                Center(
                  child: QsText(
                    logic.editable ? "完成" : "编辑",
                    color: logic.editable ? Colours.main : Colours.text,
                    fontWeight: FontWeight.w500,
                  ).paddingSymmetric(horizontal: 16, vertical: 5).tap(
                    () {
                      if (logic.editable) {
                        Utils.onEvent('sjpd_pdbj_pdbj',
                            params: {'sjpd_pdbj_pdbj': '2'});
                      } else {
                        Utils.onEvent('sjpd_pdbj_pdbj',
                            params: {'sjpd_pdbj_pdbj': '1'});
                      }
                      logic.clickEdit();
                    },
                  ),
                )
              ],
            ),
            body: Container(
              color: const Color(0xFFF5F5F5),
              child: Column(
                children: [
                  _selectedChannels(),
                  const SizedBox(height: 10),
                  _areaBar(),
                  Expanded(
                      child: Row(
                    children: [_leftList(), Expanded(child: _contentList())],
                  ))
                ],
              ),
            ),
          );
        });
  }

  Widget _selectedChannels() {
    const itemwidth = 36 + 18;
    const ratio = itemwidth / 75;
    final space = (Get.width - 32) - (36 + 18) * 5;
    final children = logic.myChannels
        .map((e) => SelectItemWidget(
            key: ValueKey(e.channelId),
            imgUrl: e.channelLogo ?? "",
            name: e.channelName ?? "",
            selected: logic.editable ? true : null,
            longPress: logic.editable ? null : () => logic.editable = true,
            selectFn: () {
              log("click item");
              if (!logic.editable) {
                Get.back<int?>(result: e.channelId);
                return;
              }
              if (logic.myChannels.length == 1) {
                Toast.text("我的频道至少保留一个赛事");
                return;
              }
              logic.myChannels.remove(e);
              logic.myChannelsMap.remove(e.channelId);
              update();
            }))
        .toList();
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      height: 200,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const QsText("我的频道", fontSize: 16),
              const Spacer(),
              if (!logic.editable)
                const QsText("点击进入赛事，长按编辑，拖拽排序",
                    color: Colours.grey99, fontSize: 12)
            ],
          ).marginSymmetric(horizontal: 0),
          const SizedBox(height: 16),
          Expanded(
            child: children.isEmpty
                ? Container()
                : DraggableGridViewBuilder(
                    shrinkWrap: false,
                    isOnlyLongPress: false,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 5,
                        childAspectRatio: ratio,
                        crossAxisSpacing: space / 4),
                    children: children
                        .map((e) => DraggableGridItem(
                            child: e, isDraggable: logic.editable))
                        .toList(),
                    dragCompletion: (list, beforeIndex, afterIndex) {
                      final item = logic.myChannels.removeAt(beforeIndex);
                      logic.myChannels.insert(afterIndex, item);
                      update();
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _areaBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      height: 44,
      child: ListView(
        clipBehavior: Clip.none,
        scrollDirection: Axis.horizontal,
        children: [
          ...logic.areas.map(
            (e) {
              return Container(
                margin: const EdgeInsets.only(right: 10),
                alignment: Alignment.center,
                child: Container(
                  width: 60,
                  height: 24,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: e.area == logic.area?.area
                              ? Colours.main
                              : Colours.grey666666),
                      borderRadius: BorderRadius.circular(12)),
                  child: QsText(
                    "${e.area}",
                    color: e.area == logic.area?.area
                        ? Colours.main
                        : Colours.grey666666,
                  ),
                ).tap(() {
                  logic.area = e;
                  if (e.list?.isNotEmpty ?? false) {
                    logic.selectCountry = e.list?.first.country ?? "";
                  }
                }),
              );
            },
          )
        ],
      ),
    );
  }

  Widget _leftList() {
    return Container(
      width: 80,
      color: Colours.greyF5F7FA,
      child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: ListView(
          controller: logic.leftController,
          children: [
            ...(logic.area?.list ?? []).map((ChannelCountryEntity e) {
              final selected = logic.selectCountry == e.country;
              return Container(
                color: selected ? Colors.white : null,
                height: 44,
                child: Row(
                  children: [
                    Container(
                      width: 3,
                      height: 24,
                      decoration: BoxDecoration(
                          color: selected ? Colours.main : null,
                          borderRadius: BorderRadius.horizontal(
                              right: Radius.circular(3))),
                    ),
                    Expanded(
                        child: QsText(
                      e.country ?? "",
                      maxLines: 2,
                      textAlign: TextAlign.center,
                      fontSize: 13,
                      color: selected ? Colours.main : Colours.text,
                    )),
                    const SizedBox(width: 3)
                  ],
                ),
              ).tap(() {
                final index = logic.area?.list?.indexOf(e) ?? -1;
                log("click left list $index");
                if (index < 0 || index >= (logic.area?.list?.length ?? 0)) {
                  return;
                }
                logic.selectCountry = e.country ?? "";
                logic.contentController.jumpTo(index: index);
              });
            })
          ],
        ),
      ),
    );
  }

  Widget _contentList() {
    final contentWidth = (Get.width - 80 - 16);
    const itemWidth = 36 + 18;
    const ratio = itemWidth / 75;
    final space = contentWidth - itemWidth * 4;
    log("content width = $contentWidth itemwidth = $itemWidth");
    return Container(
        padding: const EdgeInsets.all(8),
        color: Colors.white,
        child: ListViewObserver(
          controller: logic.contentController,
          onObserve: (p0) {
            final countries = logic.area?.list;
            final index = p0.firstChild?.index;
            if (countries != null &&
                index != null &&
                countries.length > index) {
              logic.selectCountry = countries[index].country ?? "";
              final offset = index * 44.0;
              if (logic.leftController.offset > offset) {
                logic.leftController.animateTo(offset,
                    duration: const Duration(milliseconds: 200),
                    curve: Curves.linear);
              } else if (logic.leftController.offset + 300 < offset) {
                logic.leftController.animateTo(offset - 300,
                    duration: const Duration(milliseconds: 200),
                    curve: Curves.linear);
              }
              update();
            }
          },
          child: ListView.builder(
              controller: logic.scrollController,
              itemCount: logic.area?.list?.length ?? 0,
              itemBuilder: (context, index) {
                final ChannelCountryEntity country =
                    (logic.area?.list?[index])!;
                final list = (country.list ?? []).filter(
                    (item) => logic.myChannelsMap[item.channelId ?? 0] == null);
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                        height: 38,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        child: QsText(
                          country.country ?? "",
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        )),
                    if (list.isEmpty)
                      Container(
                        height: 75,
                        alignment: Alignment.center,
                        child: const QsText(
                          "已全部添加到我的频道",
                          fontSize: 12,
                        ),
                      ),
                    if (list.isNotEmpty)
                      GridView.builder(
                        itemCount: list.length,
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4,
                            crossAxisSpacing: space / 3,
                            childAspectRatio: ratio),
                        itemBuilder: (context, index) {
                          final channel = list[index];
                          return SelectItemWidget(
                              imgUrl: channel.channelLogo ?? "",
                              name: channel.channelName ?? "",
                              selected: false,
                              longPress: null,
                              // longPress: logic.editable
                              //   ? null : () {
                              //   logic.editable = true;
                              //     update();
                              //   },
                              selectFn: () {
                                // if (!logic.editable) { return; }
                                logic.myChannels.add(channel);
                                logic.myChannelsMap[channel.channelId ?? 0] =
                                    channel;
                                update();
                                logic.updateMyChannels();
                              });
                        },
                      ).marginOnly(bottom: 10)
                  ],
                );
              }),
        ));
  }
}
